//
//  KWTGroupAddPlantVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2024/10/15.
//

#import "KWTGroupAddPlantVC.h"
#import "RHSearchView.h"
#import "KWTStationListCell.h"
#import "RHPlantModel.h"
#import "KWTPlantGroupModel.h"

@interface KWTGroupAddPlantVC ()<UITableViewDelegate,UITableViewDataSource,QMUITextFieldDelegate>
@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSMutableArray *plantListArr;

@property (nonatomic ,strong) NSMutableArray *plantSelectArr;

@property (nonatomic, strong) RHSearchView *searchView;

@property (nonatomic, assign) RequestType requestType;
//当前页数
@property (nonatomic, assign) NSInteger currentPage;
//总页数
@property (nonatomic, assign) NSInteger totalPage;
//每页多少条数据
@property (nonatomic, assign) NSInteger numOfPage;

@property (nonatomic ,copy) NSString *keyCode;
@end

@implementation KWTGroupAddPlantVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"添加站点".rh_localized;
    self.requestType = RequestTypeRefresh;
    self.currentPage = 1;
    self.numOfPage = 20;
    [self setupUI];
    [self getPlantList];
}

- (void)setupUI{
    kWeakSelf;
    self.plantListArr = [NSMutableArray array];
    self.plantSelectArr = [NSMutableArray array];
    //搜索栏
    _searchView = [[RHSearchView alloc]initWithFrame:CGRectMake(5, 0, kUI_WINDOW_W-10, 55)];
    [self.view addSubview:_searchView];
    _searchView.delegate = self;
    _searchView.searchTextField.placeholder = @"请输入关键字".rh_localized;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView registerClass:[KWTStationListCell class] forCellReuseIdentifier:@"KWTStationListCell"];
    [self.view addSubview:_tableView];
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    
    QMUIButton *createBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [createBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [createBtn setTitle:@"确认".rh_localized forState:UIControlStateNormal];
    [createBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [createBtn.layer setCornerRadius:8];
    [createBtn setBackgroundColor:CMainColorGreen];
    [self.view addSubview:createBtn];
    [createBtn addTarget:self action:@selector(addPlantToGroup) forControlEvents:UIControlEventTouchUpInside];
    [createBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(50);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(weakSelf.searchView.mas_bottom);
        make.bottom.equalTo(createBtn.mas_top).offset(-10);
    }];
  
    [_tableView addHeaderRefresh:^{
        [weakSelf.tableView.mj_footer resetNoMoreData];
        weakSelf.requestType = RequestTypeRefresh;
        weakSelf.currentPage = 1;
        weakSelf.keyCode = @"";
        [weakSelf getPlantList];
      
    }];
    
    [_tableView addBackFooterRefresh:^{
        weakSelf.requestType = RequestTypeAdd;
        weakSelf.currentPage++;
        [weakSelf getPlantList];
    }];
}


#pragma mark ---------- 获取可添加的电站列表 -----------
-(void)getPlantList
{
    NSString *status = @"";
    
    [QMUITips showLoadingInView:self.view];
    
    //获取自己的电站列表
    NSDictionary *para = @{@"pageNum":@(self.currentPage),
                           @"pageSize":@(self.numOfPage),
                           @"status":status,
                           @"plantName":ValidNullData(self.keyCode),
                           @"typeCode":self.groupModel.type
    };
    [RHPlantModel startGetWithCompletionAPIKey:H_plantListCanAddToGroup argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            NSInteger total = [request.responseObject[@"total"] integerValue];
            self.totalPage = total%self.numOfPage? total/self.numOfPage+1 : total/self.numOfPage;
            NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
            //下拉刷新
            if(self.requestType == RequestTypeRefresh){
                [self.tableView endHeaderRefresh];
                self.plantListArr = arr;
            }else{//上拉加载
                [self.tableView endFooterRefresh];
                [self.plantListArr addObjectsFromArray:arr];
            }
            if(self.currentPage >= self.totalPage){
                [self.tableView endFooterRefreshWithNoMoreData];
            }
            [self.tableView reloadData];
            if(self.plantListArr.count == 0){
                [self.tableView endFooterRefreshWithNoMoreData];
            }
        }

    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [QMUITips hideAllToastInView:self.view animated:YES];
        [self.tableView endHeaderRefresh];
    }];

}

//分组添加电站 
-(void)addPlantToGroup
{
    if (self.plantSelectArr.count == 0) {
        return;
    }
    NSMutableArray *mtbArr = [NSMutableArray array];
    [self.plantSelectArr enumerateObjectsUsingBlock:^(RHPlantModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [mtbArr addObject:@(obj.plant_id)];
    }];
    [QMUITips showLoadingInView:kApplication.keyWindow];
  
    NSDictionary *para = @{@"groupId":@(self.groupModel.groupId),
                           @"plantId":mtbArr
    };
    [RHPlantModel startWithCompletionAPIKey:H_groupAddPlant argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"成功".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter]postNotificationName:PlantListOfGroupNeedUpdateNotification object:nil];
                [self.navigationController popViewControllerAnimated:YES];
            });
        }

    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.plantListArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KWTStationListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KWTStationListCell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.model = self.plantListArr[indexPath.row];
    
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RHPlantModel *model = self.plantListArr[indexPath.row];
    model.isSelected = !model.isSelected;
    if(model.isSelected){
        [self.plantSelectArr addObject:model];
    }else{
        [self.plantSelectArr removeObject:model];
    }
    
    [self.tableView reloadData];
   
    
}


#pragma mark ------- textField delegate
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    self.keyCode = textField.text;
    [self getPlantList];
    [self.searchView resignFirstResponder];
    
}


- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    self.keyCode = @"";
    [self getPlantList];
    [self.searchView resignFirstResponder];
    return YES;
}
@end
